package com.zjuee.web.ledger.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zjuee.base.constant.DictionaryConstants;
import com.zjuee.base.dto.common.login.LoginDto;
import com.zjuee.base.exception.ServiceException;
import com.zjuee.base.model.common.company.Company;
import com.zjuee.base.model.common.company.CompanyLicenseGroup;
import com.zjuee.base.model.common.plan.PlanDanger;
import com.zjuee.base.model.common.plan.PlanSolid;
import com.zjuee.base.utils.DateUtils;
import com.zjuee.base.dto.common.ledger.LedgerDisposeGatherDto;
import com.zjuee.base.model.common.ledger.LedgerDispose;
import com.zjuee.base.model.common.ledger.LedgerDisposeBill;
import com.zjuee.base.model.common.ledger.LedgerDisposeGather;
import com.zjuee.service.*;
import com.zjuee.service.company.service.CompanyService;
import com.zjuee.web.company.mapper.CompanyLicenseGroupMapper;
import com.zjuee.web.ledger.mapper.LedgerDisposeBillMapper;
import com.zjuee.web.ledger.mapper.LedgerDisposeGatherMapper;
import com.zjuee.web.ledger.mapper.LedgerDisposeMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wu liang
 * @since 1.0
 */
@Slf4j
@Service
public class LedgerDisposeServiceImpl implements LedgerDisposeService {

    @Resource
    LedgerDisposeGatherMapper ledgerDisposeGatherMapper;
    @Resource
    LedgerDisposeBillMapper ledgerDisposeBillMapper;
    @Resource
    LedgerDisposeMapper ledgerDisposeMapper;
    @Resource
    PlanDangerService planDangerService;
    @Resource
    PlanSolidService planSolidService;
    @Resource
    CompanyService companyService;
    @Resource
    CompanyLicenseGroupMapper companyLicenseGroupMapper;
    @Resource
    private LedgerDangerSubtotalService ledgerDangerSubtotalService;

    @Resource
    private LedgerSolidSubtotalService ledgerSolidSubtotalService;
    @Resource
    LoginDto loginDto;


    @Override
    @Transactional
    public Long add(LedgerDispose ledgerDispose) {
        Company company = companyService.selectById(loginDto.getOrgBusinessId(),null).getCompany();
        if (company==null){
            throw new ServiceException("企业信息错误!");
        }
        ledgerDispose.setWldModel(ledgerDispose.getWldType().substring(0, 1));

        //如果是医废转换重量单位
        if (DictionaryConstants.TYPE_MEDICAL.equals(ledgerDispose.getWldType())) {
            conversion(ledgerDispose);
        }

        //如果是危废扣除许可证的量
        if (DictionaryConstants.MODEL_DANGER.equals(Integer.parseInt(ledgerDispose.getWldModel()))) {
            boolean result = updateCompanyLicense(ledgerDispose, company);
            if (!result) {
                throw new ServiceException("保存失败!");
            }
        }

        //查询年度处置台账汇总表
        LedgerDisposeGather ledgerDisposeGatherCon = new LedgerDisposeGather();
        ledgerDisposeGatherCon.setWldgCode(ledgerDispose.getWldScode());
        ledgerDisposeGatherCon.setWldgType(Integer.parseInt(ledgerDispose.getWldType()));
        Integer wldMark = Integer.parseInt(ledgerDispose.getWldMark());
        if (wldMark== DictionaryConstants.WLD_MARK_URGENT){
            wldMark= DictionaryConstants.WLD_MARK_COMMON;
        }else {
            wldMark=Integer.parseInt(ledgerDispose.getWldMark());
        }
        ledgerDisposeGatherCon.setWldgMark(wldMark);
        ledgerDisposeGatherCon.setBciId(company.getId());
        ledgerDisposeGatherCon.setWldgYear(String.valueOf(DateUtils.getYear(new Date())));
        ledgerDisposeGatherCon.setWldgDisposeMode(ledgerDispose.getWldDisposeType());
        ledgerDisposeGatherCon.setWldgDisposeSmode(ledgerDispose.getWldDisposeStype());

        LedgerDisposeGather ledgerDisposeGather = ledgerDisposeGatherMapper.findOneByCondition(ledgerDisposeGatherCon);
        BigDecimal currStock = BigDecimal.ZERO;
        Date date = new Date();

        //如果是初次填写处置台账
        if (DictionaryConstants.WL_INIT_IS.equals(ledgerDispose.getWldInit())) {
            //普通处置台账填报
            if (Integer.parseInt(ledgerDispose.getWldMark())== DictionaryConstants.WLD_MARK_COMMON) {
                //当前库存    当前库存=上年底库存+当年线下转入量-当年处置量-当年线下处置量
                currStock = ledgerDisposeGather == null ?
                        ledgerDispose.getWldPreStock()
                                .add(ledgerDispose.getWldThisShift())
                                .subtract(ledgerDispose.getWldDispose()).subtract(ledgerDispose.getWldThisDispose())
                        : ledgerDisposeGather.getWldgStock()
                        .add(ledgerDispose.getWldPreStock())
                        .add(ledgerDispose.getWldThisShift())
                        .subtract(ledgerDispose.getWldDispose())
                        .subtract(ledgerDispose.getWldThisDispose());
                ledgerDispose.setWldNumber(BigDecimal.ZERO);
            }

            //应急处置台账填报
            if (DictionaryConstants.WLD_MARK_URGENT.equals(ledgerDispose.getWldMark())) {
                //当前库存    当前库存= 上年底库存+转入量+线下转入量-处置量-当年线下处置量
                currStock = ledgerDisposeGather == null ?
                        ledgerDispose.getWldPreStock().add(ledgerDispose.getWldNumber()).add(ledgerDispose.getWldThisShift()).subtract(ledgerDispose.getWldDispose()).subtract(ledgerDispose.getWldThisDispose())
                        : ledgerDisposeGather.getWldgStock().add(ledgerDispose.getWldNumber()).subtract(ledgerDispose.getWldDispose());
            }

            //比对库存是否计算一致
            if (currStock.compareTo(ledgerDispose.getWldStock()) != 0 || currStock.compareTo(BigDecimal.ZERO) < 0) {
                TransactionAspectSupport.currentTransactionStatus().isRollbackOnly();
                throw new ServiceException("保存失败!");
            }

            //更新或插入ledgerDisposeGather
            if (ledgerDisposeGather == null) {
                ledgerDisposeGather = new LedgerDisposeGather();
                ledgerDisposeGather.setBciId(company.getId());
                ledgerDisposeGather.setWldgCode(ledgerDispose.getWldScode());
                ledgerDisposeGather.setWldgBcode(ledgerDispose.getWldBcode());
                ledgerDisposeGather.setWldgYear(String.valueOf(DateUtils.getYear(new Date())));
                ledgerDisposeGather.setWldgName(ledgerDispose.getWldScode());
                ledgerDisposeGather.setWldgModel(Integer.parseInt(ledgerDispose.getWldModel()));
                ledgerDisposeGather.setWldgType(Integer.parseInt(ledgerDispose.getWldType()));
                ledgerDisposeGather.setWldgDisposeMode(ledgerDispose.getWldDisposeType());
                ledgerDisposeGather.setWldgDisposeSmode(ledgerDispose.getWldDisposeStype());
                ledgerDisposeGather.setWldgUnderDispose(ledgerDispose.getWldThisDispose());
                ledgerDisposeGather.setWldgUnderShift(ledgerDispose.getWldThisShift());
                ledgerDisposeGather.setWldgTotalShift(ledgerDispose.getWldThisShift().add(ledgerDispose.getWldNumber()));
                ledgerDisposeGather.setWldgTotalDispose(ledgerDispose.getWldThisDispose().add(ledgerDispose.getWldDispose()));
                ledgerDisposeGather.setWldgChange(BigDecimal.ZERO);
                ledgerDisposeGather.setWldgCreateTime(date);
                ledgerDisposeGather.setWldgModifiedTime(date);
                ledgerDisposeGather.setWldgCreator(loginDto.getUserName());
                ledgerDisposeGather.setWldgCanDelete(DictionaryConstants.COMMON_CHOOSE_DEFAULT.toString());
                ledgerDisposeGather.setWldgCanEdit(DictionaryConstants.COMMON_CHOOSE_DEFAULT.toString());
                ledgerDisposeGather.setWldgMark(wldMark);
                ledgerDisposeGather.setWldgPreStock(ledgerDispose.getWldPreStock());
                ledgerDisposeGather.setWldgStock(currStock);
                ledgerDisposeGatherMapper.insert(ledgerDisposeGather);
            } else {
                ledgerDisposeGather.setWldgUnderShift(ledgerDispose.getWldThisShift());
                //转入量总计 = 现有转入总量+线下转入量+转入量
                ledgerDisposeGather.setWldgTotalShift(ledgerDisposeGather.getWldgTotalShift().add(ledgerDispose.getWldThisShift()).add(ledgerDispose.getWldNumber()));
                //处置量总计 = 现有处置总量+线上处置量+线下处置量
                ledgerDisposeGather.setWldgTotalDispose(ledgerDisposeGather.getWldgTotalDispose().add(ledgerDispose.getWldDispose()).add(ledgerDispose.getWldThisDispose()));
                ledgerDisposeGather.setWldgModifier(loginDto.getUserName());
                ledgerDisposeGather.setWldgModifiedTime(date);
                ledgerDisposeGather.setWldgPreStock(ledgerDispose.getWldPreStock());
                ledgerDisposeGather.setWldgStock(currStock);
                ledgerDisposeGatherMapper.updateById(ledgerDisposeGather);
            }

            //插入上年度处置汇总台账
            LedgerDisposeGather preLedgerDisposeGather = new LedgerDisposeGather();
            preLedgerDisposeGather.setWldgCode(ledgerDispose.getWldScode());
            preLedgerDisposeGather.setWldgBcode(ledgerDispose.getWldBcode());
            preLedgerDisposeGather.setBciId(company.getId());
            preLedgerDisposeGather.setWldgMark(wldMark);
            preLedgerDisposeGather.setWldgYear(Integer.valueOf(ledgerDisposeGather.getWldgYear()) - 1 + "");
            preLedgerDisposeGather.setWldgName(ledgerDispose.getWldScode());
            preLedgerDisposeGather.setWldgModel(Integer.parseInt(ledgerDispose.getWldModel()));
            preLedgerDisposeGather.setWldgType(Integer.parseInt(ledgerDispose.getWldType()));
            preLedgerDisposeGather.setWldgCreateTime(date);
            preLedgerDisposeGather.setWldgCreator(loginDto.getUserName());
            preLedgerDisposeGather.setWldgDisposeMode(ledgerDispose.getWldDisposeType());
            preLedgerDisposeGather.setWldgDisposeSmode(ledgerDispose.getWldDisposeStype());
            preLedgerDisposeGather.setWldgStock(ledgerDispose.getWldPreStock());
            //转入量总计 = 上年转入量
            preLedgerDisposeGather.setWldgTotalShift(ledgerDispose.getWldPreShift());
            //处置量总计 = 上年处置量
            preLedgerDisposeGather.setWldgTotalDispose(ledgerDispose.getWldPreDispose());
            preLedgerDisposeGather.setWldgUnderShift(BigDecimal.ZERO);
            preLedgerDisposeGather.setWldgUnderDispose(BigDecimal.ZERO);
            preLedgerDisposeGather.setWldgPreStock(BigDecimal.ZERO);
            preLedgerDisposeGather.setWldgChange(BigDecimal.ZERO);
            preLedgerDisposeGather.setWldgModifier(loginDto.getUserName());
            preLedgerDisposeGather.setWldgModifiedTime(date);
            preLedgerDisposeGather.setWldgCanDelete(DictionaryConstants.COMMON_CHOOSE_DEFAULT);
            preLedgerDisposeGather.setWldgCanEdit(DictionaryConstants.COMMON_CHOOSE_DEFAULT);
            ledgerDisposeGatherMapper.updateById(preLedgerDisposeGather);
            ledgerDispose.setWldInit(DictionaryConstants.WL_INIT_IS);
        } else {
            //非初次填报 且当年台账没有生成
            if (ledgerDisposeGather == null) {
                ledgerDisposeGather = new LedgerDisposeGather();
                ledgerDisposeGatherCon.setWldgYear(String.valueOf(Integer.valueOf(ledgerDisposeGatherCon.getWldgYear()) - 1));
                //查询上年处置台账
                LedgerDisposeGather ledgerDisposeGatherPre = ledgerDisposeGatherMapper.findOneByCondition(ledgerDisposeGatherCon);

                if (ledgerDisposeGatherPre == null) {
                    TransactionAspectSupport.currentTransactionStatus().isRollbackOnly();
                    throw new ServiceException("保存失败! 上年台账不存在");
                }

                ledgerDisposeGather.setWldgStock(ledgerDisposeGatherPre.getWldgStock().subtract(ledgerDispose.getWldDispose()));

                if (ledgerDisposeGather.getWldgStock().compareTo(ledgerDispose.getWldStock()) != 0 || ledgerDisposeGather.getWldgStock().compareTo(BigDecimal.ZERO) < 0) {
                    TransactionAspectSupport.currentTransactionStatus().isRollbackOnly();
                    throw new ServiceException("保存失败! 库存计算不正确");
                }
                ledgerDisposeGather.setBciId(ledgerDisposeGatherPre.getBciId());
                ledgerDisposeGather.setWldgYear(String.valueOf(DateUtils.getYear(new Date())));
                ledgerDisposeGather.setWldgCode(ledgerDisposeGatherPre.getWldgCode());
                ledgerDisposeGather.setWldgBcode(ledgerDisposeGatherPre.getWldgBcode());
                ledgerDisposeGather.setWldgModel(ledgerDisposeGatherPre.getWldgModel());
                ledgerDisposeGather.setWldgType(ledgerDisposeGatherPre.getWldgType());
                ledgerDisposeGather.setWldgMark(ledgerDisposeGatherPre.getWldgMark());
                ledgerDisposeGather.setWldgDisposeMode(ledgerDisposeGatherPre.getWldgDisposeMode());
                ledgerDisposeGather.setWldgDisposeSmode(ledgerDisposeGatherPre.getWldgDisposeSmode());
                ledgerDisposeGather.setWldgTotalDispose(ledgerDispose.getWldDispose());
                ledgerDisposeGather.setWldgTotalShift(BigDecimal.ZERO);
                ledgerDisposeGather.setWldgUnderDispose(BigDecimal.ZERO);
                ledgerDisposeGather.setWldgPreStock(ledgerDisposeGatherPre.getWldgStock());
                ledgerDisposeGather.setWldgName(ledgerDisposeGatherPre.getWldgName());
                ledgerDisposeGather.setWldgUnderShift(BigDecimal.ZERO);
                ledgerDisposeGather.setWpiId(ledgerDisposeGatherPre.getWpiId());
                ledgerDisposeGather.setWldgChange(BigDecimal.ZERO);
                ledgerDisposeGather.setWldgCanEdit(DictionaryConstants.COMMON_CHOOSE_DEFAULT);
                ledgerDisposeGather.setWldgCanDelete(DictionaryConstants.COMMON_CHOOSE_DEFAULT);
                ledgerDisposeGather.setWldgCreator(loginDto.getUserName());
                ledgerDisposeGather.setWldgCreateTime(new Date());
                ledgerDisposeGather.setWldgModifiedTime(new Date());
                ledgerDisposeGatherMapper.insert(ledgerDisposeGather);
            } else {
                //普通处置台账填报
                if (Integer.parseInt(ledgerDispose.getWldMark())== DictionaryConstants.WLD_MARK_COMMON) {
                    //计算当前库存(非初次填报)   当前库存=年度汇总表库存-处置量
                    currStock = ledgerDisposeGather.getWldgStock().subtract(ledgerDispose.getWldDispose());
                }

                //应急处置台账填报
                if (DictionaryConstants.WLD_MARK_URGENT.equals(ledgerDispose.getWldMark())) {
                    //计算当前库存(非初次填报)   当前库存=年度汇总表库存+转入量-处置量
                    currStock = ledgerDisposeGather.getWldgStock().add(ledgerDispose.getWldNumber()).subtract(ledgerDispose.getWldDispose());
                    ledgerDisposeGather.setWldgTotalShift(ledgerDisposeGather.getWldgTotalShift().add(ledgerDispose.getWldNumber()));
                }


                //与前端传过来的库存进行比对校验
                if (currStock.compareTo(ledgerDispose.getWldStock()) != 0 || currStock.compareTo(BigDecimal.ZERO) < 0) {
                    TransactionAspectSupport.currentTransactionStatus().isRollbackOnly();
                     throw new ServiceException("保存失败!");
                }

                //更新年度汇总表
                ledgerDisposeGather.setWldgTotalDispose(ledgerDisposeGather.getWldgTotalDispose().add(ledgerDispose.getWldDispose()));
                ledgerDisposeGather.setWldgStock(currStock);
                ledgerDisposeGather.setWldgModifier(loginDto.getUserName());
                ledgerDisposeGather.setWldgModifiedTime(date);
                ledgerDisposeGather.setWldgCanDelete(DictionaryConstants.COMMON_CHOOSE_NOT);
                ledgerDisposeGatherMapper.updateById(ledgerDisposeGather);
                ledgerDispose.setWldInit(DictionaryConstants.WL_INIT_NOT);
            }
        }

        //插入处置台账填报记录
        if (Integer.parseInt(ledgerDispose.getWldMark())!= DictionaryConstants.WLD_MARK_URGENT) {
            ledgerDispose.setWldNumber(BigDecimal.ZERO);
        }

        ledgerDispose.setBciId(company.getId());
        ledgerDispose.setWldType(ledgerDispose.getWldType());
        ledgerDispose.setWldStock(currStock);
        ledgerDispose.setWldCreateTime(date);
        ledgerDispose.setWldCreator(loginDto.getUserName());


        //插入处置台账明细记录
        LedgerDisposeBill ledgerDisposeBill = new LedgerDisposeBill();
        ledgerDisposeBill.setBciId(company.getId());
        ledgerDisposeBill.setWldgId(ledgerDisposeGather.getId());
        ledgerDisposeBill.setWldbModel(Integer.parseInt(ledgerDispose.getWldModel()));
        ledgerDisposeBill.setWldbType(Integer.parseInt(ledgerDispose.getWldType()));
        ledgerDisposeBill.setWldbFrom(DictionaryConstants.WL_FROM_WRITE);
        ledgerDisposeBill.setWldbMark(wldMark);
        ledgerDisposeBill.setWldbBcode(ledgerDispose.getWldBcode());
        ledgerDisposeBill.setWldbScode(ledgerDispose.getWldScode());
        ledgerDisposeBill.setWldbName(ledgerDispose.getWldScode());
        ledgerDisposeBill.setWldbStock(ledgerDisposeGather.getWldgStock());
        ledgerDisposeBill.setWldbDispose(ledgerDispose.getWldDispose());
        ledgerDisposeBill.setWldbRemark(DictionaryConstants.WLD_MARK_URGENT.equals(ledgerDispose.getWldMark()) ? "应急台账 " + ledgerDispose.getWldRemark() : ledgerDispose.getWldRemark());
        ledgerDisposeBill.setWldbShift(ledgerDispose.getWldNumber());
        ledgerDisposeBill.setWldbUrgentSheet(DictionaryConstants.WLD_MARK_URGENT.equals(ledgerDispose.getWldMark())
                ? ledgerDispose.getWldUrgentSheet() : null);
        ledgerDisposeBill.setWldbCreator(loginDto.getUserName());
        ledgerDisposeBill.setWldbCreateTime(date);
        ledgerDisposeBillMapper.insert(ledgerDisposeBill);
        //最后将填报台账类型改为普通台账
        ledgerDispose.setWldMark(String.valueOf(DictionaryConstants.WLD_MARK_COMMON));
        ledgerDispose.setWldThisDispose(ledgerDispose.getWldThisDispose()==null?BigDecimal.ZERO:ledgerDispose.getWldThisDispose());
        ledgerDispose.setWldThisShift(ledgerDispose.getWldThisShift()==null?BigDecimal.ZERO:ledgerDispose.getWldThisShift());
        ledgerDispose.setWldPreDispose(ledgerDispose.getWldPreDispose()==null?BigDecimal.ZERO:ledgerDispose.getWldPreDispose());
        ledgerDispose.setWldPreShift(ledgerDispose.getWldPreShift()==null?BigDecimal.ZERO:ledgerDispose.getWldPreShift());
        ledgerDispose.setWldPreStock(ledgerDispose.getWldPreStock()==null?BigDecimal.ZERO:ledgerDispose.getWldPreStock());
        ledgerDisposeMapper.insert(ledgerDispose);
        // 入统计表
        if (DictionaryConstants.TYPE_DANGER.equals(ledgerDispose.getWldType())
                || DictionaryConstants.TYPE_MEDICAL.equals(ledgerDispose.getWldType())) {
            ledgerDangerSubtotalService.ledgerDangerDisposeReport(ledgerDispose, DictionaryConstants.VL_LEDGER_NOMAL);

        } else {
            ledgerSolidSubtotalService.ledgerSolidDisposeReport(ledgerDispose, DictionaryConstants.VL_LEDGER_NOMAL);

        }
        return 1l;
    }

    /**
     * 单位换算 千克-->吨
     *
     * @param ledgerDispose
     */
    private void conversion(LedgerDispose ledgerDispose) {
        BigDecimal number = new BigDecimal(1000);
        BigDecimal zero = BigDecimal.ZERO;
        ledgerDispose.setWldDispose(ledgerDispose.getWldDispose() != null ? ledgerDispose.getWldDispose().divide(number) : zero);
        ledgerDispose.setWldStock(ledgerDispose.getWldStock() != null ? ledgerDispose.getWldStock().divide(number) : zero);
        ledgerDispose.setWldNumber(ledgerDispose.getWldNumber() != null ? ledgerDispose.getWldNumber().divide(number) : zero);
        ledgerDispose.setWldPreShift(ledgerDispose.getWldPreShift() != null ? ledgerDispose.getWldPreShift().divide(number) : zero);
        ledgerDispose.setWldThisDispose(ledgerDispose.getWldThisDispose() != null ? ledgerDispose.getWldThisDispose().divide(number) : zero);
        ledgerDispose.setWldThisShift(ledgerDispose.getWldThisShift() != null ? ledgerDispose.getWldThisShift().divide(number) : zero);
        ledgerDispose.setWldPreStock(ledgerDispose.getWldPreStock() != null ? ledgerDispose.getWldPreStock().divide(number) : zero);
        ledgerDispose.setWldPreDispose(ledgerDispose.getWldPreDispose() != null ? ledgerDispose.getWldPreDispose().divide(number) : zero);
    }

    private boolean updateCompanyLicense(LedgerDispose ledgerDispose, Company company) {
        //查询剩余处置量
        List<CompanyLicenseGroup> companyLicenseGroupList = companyLicenseGroupMapper.findByCodeAndTypeAndBciId(company.getId(), ledgerDispose.getWldScode(), ledgerDispose.getWldBcode(), ledgerDispose.getWldDisposeType(), ledgerDispose.getWldDisposeStype());
        //本次填报处置量
        BigDecimal disposeAmount = ledgerDispose.getWldDispose().add(ledgerDispose.getWldThisDispose() == null ? BigDecimal.ZERO : ledgerDispose.getWldThisDispose());

        if (disposeAmount.compareTo(BigDecimal.ZERO) == 0) {
            return true;
        }

        if (companyLicenseGroupList != null && companyLicenseGroupList.size() > 0) {
            for (CompanyLicenseGroup companyLicenseGroup : companyLicenseGroupList) {
                //判断剩余处置量
                if (companyLicenseGroup.getBclgSurplusCapacity().compareTo(disposeAmount) < 0) {
                    //能扣除多少扣多少
                    disposeAmount = disposeAmount.subtract(companyLicenseGroup.getBclgSurplusCapacity());
                    companyLicenseGroup.setBclgSurplusCapacity(BigDecimal.ZERO);
                    companyLicenseGroup.setBclgUseCapacity(companyLicenseGroup.getBclgCapacity());
                    companyLicenseGroupMapper.updateById(companyLicenseGroup);
                } else {
                    //扣除本次处置量并更新
                    companyLicenseGroup.setBclgSurplusCapacity(companyLicenseGroup.getBclgSurplusCapacity().subtract(disposeAmount));
                    companyLicenseGroup.setBclgUseCapacity(companyLicenseGroup.getBclgUseCapacity().add(disposeAmount));
                    companyLicenseGroupMapper.updateById(companyLicenseGroup);
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public boolean delete(Long id, Long validateId) {
        return false;
    }

    @Override
    public boolean update(LedgerDispose type) {
        return false;
    }

    @Override
    public LedgerDispose selectById(Long id, Long validateId) {
        return null;
    }

    @Override
    public Page<LedgerDispose> list(LedgerDisposeGatherDto dto) {
        return null;
    }

    @Override
    public LambdaQueryWrapper<LedgerDispose> fuzzyQuery(LedgerDisposeGatherDto dto) {
        return null;
    }

    @Override
    public Map<String, Object> isInitLedgerDispose(LedgerDispose ledgerDispose) {
        if (ledgerDispose == null) {
            throw new ServiceException("查询失败");
        }

        Company company = companyService.selectById(loginDto.getOrgBusinessId(),null).getCompany();
        if (company==null){
            throw new ServiceException("企业信息错误!");
        }
        ledgerDispose.setBciId(company.getId());
        List<LedgerDispose> ledgerDisposeList = ledgerDisposeMapper.selectList(ledgerDispose);
        String isInit = DictionaryConstants.WL_INIT_IS;

        if (!CollectionUtils.isEmpty(ledgerDisposeList)) {
            isInit = DictionaryConstants.WL_INIT_NOT;
        }

        LedgerDisposeGather ledgerDisposeGatherCon = new LedgerDisposeGather();
        ledgerDisposeGatherCon.setBciId(company.getId());
        ledgerDisposeGatherCon.setWldgType(Integer.parseInt(ledgerDispose.getWldType()));
        ledgerDisposeGatherCon.setWldgMark(Integer.parseInt(ledgerDispose.getWldMark()));
        ledgerDisposeGatherCon.setWldgYear(String.valueOf(DateUtils.getYear(new Date())));
        ledgerDisposeGatherCon.setWldgCode(ledgerDispose.getWldScode());
        ledgerDisposeGatherCon.setWldgDisposeSmode(ledgerDispose.getWldDisposeStype());
        ledgerDisposeGatherCon.setWldgDisposeMode(ledgerDispose.getWldDisposeType());
        LedgerDisposeGather ledgerDisposeGather = ledgerDisposeGatherMapper.findOneByCondition(ledgerDisposeGatherCon);

        if (ledgerDisposeGather == null && isInit == DictionaryConstants.WL_INIT_NOT) {
            ledgerDisposeGatherCon.setWldgYear(String.valueOf(Integer.valueOf(DateUtils.getYear(new Date())) - 1));
            ledgerDisposeGather = ledgerDisposeGatherMapper.findOneByCondition(ledgerDisposeGatherCon);
        }

        //如果是收集台账
        if (Integer.parseInt(ledgerDispose.getWldMark())== DictionaryConstants.WLD_MARK_COLLECT) {
            if (ledgerDisposeGather == null) {
                if (DictionaryConstants.TYPE_DANGER.equals(ledgerDispose.getWldType())
                        || DictionaryConstants.TYPE_MEDICAL.equals(ledgerDispose.getWldType())) {
                    PlanDanger planDangerCon = new PlanDanger();
                    planDangerCon.setWpdModel(Integer.parseInt(DictionaryConstants.WP_MODEL_COLLECT));
                    planDangerCon.setWpdScode(ledgerDispose.getWldScode());
                    planDangerCon.setWpdType(Integer.parseInt(ledgerDispose.getWldType()));
                    List<PlanDanger> planDangerList = planDangerService.getPlanDanger(planDangerCon);

                    if (!CollectionUtils.isEmpty(planDangerList)) {
                        ledgerDisposeGather = new LedgerDisposeGather();
                        ledgerDisposeGather.setWldgPreStock(planDangerList.get(0).getWpdPreStock());
                    }
                } else {
                    PlanSolid planSolidCon = new PlanSolid();
                    planSolidCon.setWpsCollect(DictionaryConstants.WP_MODEL_COLLECT);
                    planSolidCon.setWpsCode(ledgerDispose.getWldScode());
                    planSolidCon.setWpsModel(Integer.parseInt(ledgerDispose.getWldModel()));
                    planSolidCon.setWpsType(Integer.parseInt(ledgerDispose.getWldType()));
                    List<PlanSolid> planSolidList = planSolidService.getPlanSolid(planSolidCon);

                    if (!CollectionUtils.isEmpty(planSolidList)) {
                        ledgerDisposeGather = new LedgerDisposeGather();
                        ledgerDisposeGather.setWldgPreStock(planSolidList.get(0).getWpsPreStock());
                    }
                }
            }
        }

        Map<String, Object> result = new HashMap<String, Object>();
        result.put("ledgerDisposeGather", ledgerDisposeGather);
        result.put("isInit", isInit);
        return result;
    }

    @Override
    @Transactional
    public Long addCollect(LedgerDispose ledgerDispose) {
        Company company = companyService.selectById(loginDto.getOrgBusinessId(),null).getCompany();
        if (company==null){
            throw new ServiceException("企业信息错误!");
        }
        ledgerDispose.setWldNumber(BigDecimal.ZERO);
        ledgerDispose.setWldDispose(BigDecimal.ZERO);
        ledgerDispose.setWldModel(ledgerDispose.getWldType().substring(0, 1));

        //如果是医废收集台账转换重量单位
        if (DictionaryConstants.TYPE_MEDICAL.equals(ledgerDispose.getWldType())) {
            conversion(ledgerDispose);
        }

        //如果是危废收集扣除许可证的量
        if (DictionaryConstants.MODEL_DANGER.equals(ledgerDispose.getWldModel())) {
            boolean result = updateCompanyLicense(ledgerDispose, company);

            if (!result) {
               throw new ServiceException("保存失败!");
            }
        }

        //查询年度处置台账汇总表
        LedgerDisposeGather ledgerDisposeGatherCon = new LedgerDisposeGather();
        ledgerDisposeGatherCon.setWldgCode(ledgerDispose.getWldScode());
        ledgerDisposeGatherCon.setWldgType(Integer.parseInt(ledgerDispose.getWldType()));
        ledgerDisposeGatherCon.setWldgMark(Integer.parseInt(ledgerDispose.getWldMark()));
        ledgerDisposeGatherCon.setBciId(company.getId());
        ledgerDisposeGatherCon.setWldgYear(String.valueOf(DateUtils.getYear(new Date())));
        ledgerDisposeGatherCon.setWldgDisposeMode(ledgerDispose.getWldDisposeType());
        ledgerDisposeGatherCon.setWldgDisposeSmode(ledgerDispose.getWldDisposeStype());
        LedgerDisposeGather ledgerDisposeGather = ledgerDisposeGatherMapper.findOneByCondition(ledgerDisposeGatherCon);

        BigDecimal currStock = BigDecimal.ZERO;
        Date date = new Date();

        //初次填写处置台账
        if (DictionaryConstants.WL_INIT_IS.equals(ledgerDispose.getWldInit())) {

            //当前库存    当前库存= 上年底库存+线下转入量-线下转出量
            currStock = ledgerDisposeGather == null ? ledgerDispose.getWldPreStock().add(ledgerDispose.getWldThisShift()).subtract(ledgerDispose.getWldThisDispose())
                    : ledgerDisposeGather.getWldgStock().add(ledgerDispose.getWldThisShift()).subtract(ledgerDispose.getWldThisDispose());

            //比对库存是否计算一致
            if (currStock.compareTo(ledgerDispose.getWldStock()) != 0 || currStock.compareTo(BigDecimal.ZERO) < 0) {
                TransactionAspectSupport.currentTransactionStatus().isRollbackOnly();
               throw new ServiceException("保存失败!");
            }

            //更新或插入ledgerDisposeGather
            if (ledgerDisposeGather == null) {
                ledgerDisposeGather = new LedgerDisposeGather();
                ledgerDisposeGather.setBciId(company.getId());
                ledgerDisposeGather.setWldgCode(ledgerDispose.getWldScode());
                ledgerDisposeGather.setWldgBcode(ledgerDispose.getWldBcode());
                ledgerDisposeGather.setWldgYear(String.valueOf(DateUtils.getYear(date)));
                ledgerDisposeGather.setWldgName(ledgerDispose.getWldScode());
                ledgerDisposeGather.setWldgModel(Integer.parseInt(ledgerDispose.getWldModel()));
                ledgerDisposeGather.setWldgType(Integer.parseInt(ledgerDispose.getWldType()));
                ledgerDisposeGather.setWldgDisposeMode(ledgerDispose.getWldDisposeType());
                ledgerDisposeGather.setWldgDisposeSmode(ledgerDispose.getWldDisposeStype());
                ledgerDisposeGather.setWldgUnderDispose(ledgerDispose.getWldThisDispose());
                ledgerDisposeGather.setWldgUnderShift(ledgerDispose.getWldThisShift());
                ledgerDisposeGather.setWldgTotalShift(ledgerDispose.getWldThisShift());
                ledgerDisposeGather.setWldgTotalDispose(ledgerDispose.getWldThisDispose());
                ledgerDisposeGather.setWldgChange(BigDecimal.ZERO);
                ledgerDisposeGather.setWldgCanDelete(DictionaryConstants.COMMON_CHOOSE_DEFAULT);
                ledgerDisposeGather.setWldgCanEdit(DictionaryConstants.COMMON_CHOOSE_DEFAULT);
                ledgerDisposeGather.setWldgCreateTime(date);
                ledgerDisposeGather.setWldgCreator(loginDto.getUserName());
                ledgerDisposeGather.setWldgMark(Integer.parseInt(ledgerDispose.getWldMark()));
                ledgerDisposeGather.setWldgPreStock(ledgerDispose.getWldPreStock());
                ledgerDisposeGather.setWldgStock(currStock);
                ledgerDisposeGatherMapper.insert(ledgerDisposeGather);
            } else {
                //转入量总计 = 现有转入总量+线下转入量
                ledgerDisposeGather.setWldgTotalShift(ledgerDisposeGather.getWldgTotalShift().add(ledgerDispose.getWldThisShift()));
                //处置量总计（转出量总计） = 现有处置（转出）总量+线下处置（转出）量
                ledgerDisposeGather.setWldgTotalDispose(ledgerDisposeGather.getWldgTotalDispose().add(ledgerDispose.getWldThisDispose()));
                ledgerDisposeGather.setWldgUnderShift(ledgerDispose.getWldThisShift());
                ledgerDisposeGather.setWldgUnderDispose(ledgerDispose.getWldThisDispose());
                ledgerDisposeGather.setWldgModifier(loginDto.getUserName());
                ledgerDisposeGather.setWldgModifiedTime(date);
                ledgerDisposeGather.setWldgPreStock(ledgerDispose.getWldPreStock());
                ledgerDisposeGather.setWldgStock(currStock);
                ledgerDisposeGatherMapper.updateById(ledgerDisposeGather);
            }



            //插入上年度处置汇总台账
            LedgerDisposeGather preLedgerDisposeGather = new LedgerDisposeGather();
            preLedgerDisposeGather.setWldgCode(ledgerDispose.getWldScode());
            preLedgerDisposeGather.setWldgBcode(ledgerDispose.getWldBcode());
            preLedgerDisposeGather.setBciId(company.getId());
            preLedgerDisposeGather.setWldgMark(Integer.parseInt(ledgerDispose.getWldMark()));
            preLedgerDisposeGather.setWldgYear(Integer.valueOf(ledgerDisposeGather.getWldgYear()) - 1 + "");
            preLedgerDisposeGather.setWldgName(ledgerDispose.getWldScode());
            preLedgerDisposeGather.setWldgModel(Integer.parseInt(ledgerDispose.getWldModel()));
            preLedgerDisposeGather.setWldgType(Integer.parseInt(ledgerDispose.getWldType()));
            preLedgerDisposeGather.setWldgDisposeMode(ledgerDispose.getWldDisposeType());
            preLedgerDisposeGather.setWldgDisposeSmode(ledgerDispose.getWldDisposeStype());
            preLedgerDisposeGather.setWldgStock(ledgerDispose.getWldPreStock());
            //转入量总计 = 上年转入量
            preLedgerDisposeGather.setWldgTotalShift(ledgerDispose.getWldPreShift());
            //处置(转出)量总计 = 上年处置(转出)量
            preLedgerDisposeGather.setWldgTotalDispose(ledgerDispose.getWldPreDispose());
            preLedgerDisposeGather.setWldgUnderShift(BigDecimal.ZERO);
            preLedgerDisposeGather.setWldgUnderDispose(BigDecimal.ZERO);
            preLedgerDisposeGather.setWldgPreStock(BigDecimal.ZERO);
            preLedgerDisposeGather.setWldgChange(BigDecimal.ZERO);
            preLedgerDisposeGather.setWldgCreateTime(date);
            preLedgerDisposeGather.setWldgCreator(loginDto.getUserName());
            preLedgerDisposeGather.setWldgModifier(loginDto.getUserName());
            preLedgerDisposeGather.setWldgModifiedTime(date);
            preLedgerDisposeGather.setWldgCanDelete(DictionaryConstants.COMMON_CHOOSE_DEFAULT);
            preLedgerDisposeGather.setWldgCanEdit(DictionaryConstants.COMMON_CHOOSE_DEFAULT);
            ledgerDisposeGatherMapper.updateById(preLedgerDisposeGather);
            ledgerDispose.setWldInit(DictionaryConstants.WL_INIT_IS);

            //插入处置台账填报记录
            ledgerDispose.setBciId(company.getId());
            ledgerDispose.setWldNumber(BigDecimal.ZERO);
            ledgerDispose.setWldModel(DictionaryConstants.TYPE_DANGER.equals(ledgerDispose.getWldType()) ? String.valueOf(DictionaryConstants.MODEL_DANGER): String.valueOf(DictionaryConstants.MODEL_SOLID));
            ledgerDispose.setWldStock(currStock);
            ledgerDispose.setWldCreateTime(date);
            ledgerDispose.setWldCreator(loginDto.getUserName());
            ledgerDispose.setWldMark(String.valueOf(DictionaryConstants.WLD_MARK_COLLECT));
            ledgerDispose.setWldThisDispose(ledgerDispose.getWldThisDispose()==null?BigDecimal.ZERO:ledgerDispose.getWldThisDispose());
            ledgerDispose.setWldThisShift(ledgerDispose.getWldThisShift()==null?BigDecimal.ZERO:ledgerDispose.getWldThisShift());
            ledgerDispose.setWldPreDispose(ledgerDispose.getWldPreDispose()==null?BigDecimal.ZERO:ledgerDispose.getWldPreDispose());
            ledgerDispose.setWldPreShift(ledgerDispose.getWldPreShift()==null?BigDecimal.ZERO:ledgerDispose.getWldPreShift());
            ledgerDispose.setWldPreStock(ledgerDispose.getWldPreStock()==null?BigDecimal.ZERO:ledgerDispose.getWldPreStock());
//            ledgerDispose.setWldCreator(ledgerDispose.getWldCreator());
            ledgerDisposeMapper.insert(ledgerDispose);

            //插入处置台账明细记录
            LedgerDisposeBill ledgerDisposeBill = new LedgerDisposeBill();
            ledgerDisposeBill.setBciId(company.getId());
            ledgerDisposeBill.setWldgId(ledgerDisposeGather.getId());
            ledgerDisposeBill.setWldbModel(Integer.parseInt(ledgerDispose.getWldModel()));
            ledgerDisposeBill.setWldbType(Integer.parseInt(ledgerDispose.getWldType()));
            ledgerDisposeBill.setWldbFrom(DictionaryConstants.WL_FROM_WRITE);
            ledgerDisposeBill.setWldbMark(Integer.parseInt(ledgerDispose.getWldMark()));
            ledgerDisposeBill.setWldbBcode(ledgerDispose.getWldBcode());
            ledgerDisposeBill.setWldbScode(ledgerDispose.getWldScode());
            ledgerDisposeBill.setWldbName(ledgerDispose.getWldScode());
            ledgerDisposeBill.setWldbStock(ledgerDisposeGather.getWldgStock());
            ledgerDisposeBill.setWldbDispose(BigDecimal.ZERO);
            ledgerDisposeBill.setWldbShift(BigDecimal.ZERO);
            ledgerDisposeBill.setWldbRemark(ledgerDispose.getWldRemark());
            ledgerDisposeBill.setWldbCreator(loginDto.getUserName());
            ledgerDisposeBill.setWldbCreateTime(date);
            ledgerDisposeBillMapper.insert(ledgerDisposeBill);
        }else {
            //非初次填报 手动初始化收集台账
            if (ledgerDisposeGather == null) {
                ledgerDisposeGather = new LedgerDisposeGather();
                ledgerDisposeGatherCon.setWldgYear(String.valueOf(Integer.valueOf(ledgerDisposeGatherCon.getWldgYear()) - 1));
                //查询上年收集台账
                LedgerDisposeGather ledgerDisposeGatherPre = ledgerDisposeGatherMapper.findOneByCondition(ledgerDisposeGatherCon);

                if (ledgerDisposeGatherPre == null) {
                    TransactionAspectSupport.currentTransactionStatus().isRollbackOnly();
                    throw new ServiceException("保存失败! 上年台账不存在");
                }

                ledgerDisposeGather.setWldgStock(ledgerDisposeGatherPre.getWldgStock());
                ledgerDisposeGather.setBciId(ledgerDisposeGatherPre.getBciId());
                ledgerDisposeGather.setWldgYear(String.valueOf(DateUtils.getYear(new Date())));
                ledgerDisposeGather.setWldgCode(ledgerDisposeGatherPre.getWldgCode());
                ledgerDisposeGather.setWldgBcode(ledgerDisposeGatherPre.getWldgBcode());
                ledgerDisposeGather.setWldgModel(ledgerDisposeGatherPre.getWldgModel());
                ledgerDisposeGather.setWldgType(ledgerDisposeGatherPre.getWldgType());
                ledgerDisposeGather.setWldgMark(ledgerDisposeGatherPre.getWldgMark());
                ledgerDisposeGather.setWldgDisposeMode(ledgerDisposeGatherPre.getWldgDisposeMode());
                ledgerDisposeGather.setWldgDisposeSmode(ledgerDisposeGatherPre.getWldgDisposeSmode());
                ledgerDisposeGather.setWldgTotalDispose(BigDecimal.ZERO);
                ledgerDisposeGather.setWldgTotalShift(BigDecimal.ZERO);
                ledgerDisposeGather.setWldgUnderDispose(BigDecimal.ZERO);
                ledgerDisposeGather.setWldgPreStock(ledgerDisposeGatherPre.getWldgStock());
                ledgerDisposeGather.setWldgName(ledgerDisposeGatherPre.getWldgName());
                ledgerDisposeGather.setWldgUnderShift(BigDecimal.ZERO);
                ledgerDisposeGather.setWpiId(ledgerDisposeGatherPre.getWpiId());
                ledgerDisposeGather.setWldgChange(BigDecimal.ZERO);
                ledgerDisposeGather.setWldgCanEdit(DictionaryConstants.COMMON_CHOOSE_DEFAULT);
                ledgerDisposeGather.setWldgCanDelete(DictionaryConstants.COMMON_CHOOSE_DEFAULT);
                ledgerDisposeGather.setWldgCreator(loginDto.getUserName());
                ledgerDisposeGather.setWldgCreateTime(new Date());
                ledgerDisposeGatherMapper.insert(ledgerDisposeGather);
            }

        }
        return 1l;
    }
}
